package mex1;

/**
 * Mex9 - shows how a group of threads accessing a single
 *        list object can "lose" data or have run-time errors.
 * 
 * @author Anthony Varghese
 */
public class Mex9 {
	private static java.util.List<String> in;
	private static final int NUMBER_OF_ITERATIONS = 20;
	/**
	 * SimpleThread - our simple thread class
	 * @author tony
	 */
	private static class SimpleThread extends Thread{
		public SimpleThread( ThreadGroup g, String id){
			super( g, id );
		}
		public void run(){
			for (int i=0; i<NUMBER_OF_ITERATIONS; i++)
				in.add( "Group: " + getThreadGroup() + " id: " + getName() + " iter: " + i );
			try {
				sleep(1000);
			} catch (InterruptedException e) {
				System.out.println("   ... thread " + getThreadGroup() + ":" + getName() + " done!");
				return;
			}
		}
	}
	
	/**
	 * main - main method for Mex8
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		System.out.println("Mex9 program starting ...");

		in = new java.util.ArrayList<String>();
		
		// We will set up a main group and two sub-groups under it:
		ThreadGroup group1 = new ThreadGroup( "Main Group" );
		ThreadGroup groupx = new ThreadGroup( group1, "Sub-group x" );
		ThreadGroup groupy = new ThreadGroup( group1, "Sub-group y" );
		final int num1 = 7;
		final int num2 = 3;
		for (int i=0; i<num1; i++)
			(new SimpleThread( groupx, "x"+i )).start();
		for (int i=0; i<num2; i++)
			(new SimpleThread( groupy, "y"+i )).start();
		System.out.println(
				"   a total of " + (num1+num2) + " threads were created \n" +
				"   with each thread creating " + NUMBER_OF_ITERATIONS + " Strings,\n" +
				"    the total number of Strings in the array should be: " + ((num1+num2) * NUMBER_OF_ITERATIONS) +"\n");

		// create an array of threads in group - so that we can
		//   join them all later
		int c = group1.activeCount();
		Thread g1[] = new Thread[ c ];
		group1.enumerate(g1);
		System.out.println(	"   a total of " + c + " threads are active. \n");


		// wait for all threads to be done:
		for (Thread t : g1)
			t.join();

		System.out.println(" Actual number of Strings in the array is " + in.size() );
		System.out.println("... program done!");
	}
}